<?php


namespace App\Http\Controllers\Admin\CustomerService;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

//客服问题
class QuestionController extends BaseController
{
    /**
     * @api {get} /customer-service/question 问题列表
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {String} created_date_start 创建日期开始
     * @apiParam {String} created_date_end 创建日期结束
     * @apiParam {String} question_name 问题名称
     * @apiParam {int} question_id 问题编号
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 2, id，序号
    "name": "如何更改昵称", 问题名称
    "sort": 275, 排序号
    "helpful_count": 36,
    "unhelpful_count": 1,
    "remark": "这里是备注", 备注
    "updated_at": "2021-07-23 07:03:07", 更新时间
    "status": 0, 状态：1：启用；0：禁用
    "helpful_rate": "97%" 有助率
    }
    ],
    "first_page_url": "http://local.qipaoadmin/customer-service/question-ist?page=1",
    "from": 1,
    "last_page": 2,
    "last_page_url": "http://local.qipaoadmin/customer-service/question-ist?page=2",
    "next_page_url": "http://local.qipaoadmin/customer-service/question-ist?page=2",
    "path": "http://local.qipaoadmin/customer-service/question-ist",
    "per_page": 10,
    "prev_page_url": null,
    "to": 10,
    "total": 17
    }
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('created_date_start', 'created_date_end', 'question_name', 'question_id', 'page', 'page_size');
        //参数校验
        $v = app('validator')->make($param,
            [
                'created_date_start' => 'date_format:Y-m-d',
                'created_date_end' => 'date_format:Y-m-d',
                'question_name' => 'string|max:20',
                'question_id' => 'integer|min:1',
                'page' => 'integer|min:1',
                'page_size' => 'integer|min:1',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $createdDateStart = $param['created_date_start'] ?? '';
        $createdDateEnd = $param['created_date_end'] ?? '';
        $questionName = $param['question_name'] ?? '';
        $questionId = $param['question_id'] ?? 0;
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($createdDateStart) {
            $where[] = ['updated_at', '>=', $createdDateStart . ' 0:0:0'];
        }
        if ($createdDateEnd) {
            $where[] = ['updated_at', '<=', $createdDateEnd . ' 23:59:59'];
        }
        if ($questionName) {
            $where[] = ['name', 'like', "%$questionName%"];
        }
        if ($questionId) {
            $where[] = ['id', '=', $questionId];
        }

        $list = app('model_customer_service_question')
            ->select('id', 'name', 'sort', 'helpful_count', 'unhelpful_count', 'remark', 'updated_at', 'status')
            ->where($where)
            ->orderBy('updated_at', 'desc')
            ->paginate($pageSize);
        foreach ($list as &$v) {
            if ($v->helpful_count == 0) {
                $v->helpful_rate = '0%';
            } else {
                $v->helpful_rate = round($v->helpful_count / ($v->helpful_count + $v->unhelpful_count) * 100) . '%';
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {post} /customer-service/question 添加问题
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {String} question_name 问题名称，必须
     * @apiParam {String} question_name_keyword 问题名称搜索关键词，多个用中文逗号隔开，最多10个，必须
     * @apiParam {String} question_answer 问题答案，必须
     * @apiParam {int} sort 排序号，建议默认1000，必须
     * @apiParam {int} valid_date_type 有效日期类型：1：永久；2：自定义，必须
     * @apiParam {String} valid_date_start 自定义开始日期，格式：yyyy-mm-dd，当valid_date_type=2时必须
     * @apiParam {String} valid_date_end 自定义结束日期，格式：yyyy-mm-dd，当valid_date_type=2时必须
     * @apiParam {int} status 状态：1：启用；0：禁用，必须
     * @apiParam {String} remark 备注
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[]}
     */
    public function add(Request $request)
    {
        $param = $request->only('question_name', 'question_name_keyword', 'question_answer', 'sort', 'valid_date_type', 'valid_date_start', 'valid_date_end', 'status', 'remark');
        //参数校验
        $v = app('validator')->make($param,
            [
                'question_name' => 'required|string|max:20',
                'question_name_keyword' => 'required|string|max:30',
                'question_answer' => 'required',
                'sort' => 'required|integer|min:0|max:65535',
                'valid_date_type' => 'required|integer|in:1,2',
                'valid_date_start' => 'required_if:valid_date_type,2|date_format:Y-m-d',
                'valid_date_end' => 'required_if:valid_date_type,2|date_format:Y-m-d',
                'status' => 'required|integer|in:0,1',
                'remark' => 'string|max:50',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $res = app('repo_customer_service_question')->addOrEdit($param);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {post} /customer-service/question/edit 编辑问题
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {int} id 问题id，必须
     * @apiParam {String} question_name 问题名称，必须
     * @apiParam {String} question_name_keyword 问题名称搜索关键词，多个用中文逗号隔开，最多6个，必须
     * @apiParam {String} question_answer 问题答案，必须
     * @apiParam {int} sort 排序号，建议默认1000，必须
     * @apiParam {int} valid_date_type 有效日期类型：1：永久；2：自定义，必须
     * @apiParam {String} valid_date_start 自定义开始日期，格式：yyyy-mm-dd，当valid_date_type=2时必须
     * @apiParam {String} valid_date_end 自定义结束日期，格式：yyyy-mm-dd，当valid_date_type=2时必须
     * @apiParam {int} status 状态：1：启用；0：禁用，必须
     * @apiParam {String} remark 备注
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":[]}
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'question_name', 'question_name_keyword', 'question_answer', 'sort', 'valid_date_type', 'valid_date_start', 'valid_date_end', 'status', 'remark');
        //参数校验
        $v = app('validator')->make($param,
            [
                'id' => 'required|integer|min:1',
                'question_name' => 'required|max:20',
                'question_name_keyword' => 'required|string|max:30',
                'question_answer' => 'required|max:65535',
                'sort' => 'required|integer|min:0|max:65535',
                'valid_date_type' => 'required|integer|in:1,2',
                'valid_date_start' => 'required_if:valid_date_type,2|date_format:Y-m-d',
                'valid_date_end' => 'required_if:valid_date_type,2|date_format:Y-m-d',
                'status' => 'required|integer|in:0,1',
                'remark' => 'string|max:50',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $res = app('repo_customer_service_question')->addOrEdit($param);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    /**
     * @api {get} /customer-service/question/detail 获取问题详情
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {int} id 问题id，必须
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "id": 20, 问题序号
    "name": "不能送礼物给主播了", 问题名称
    "answer": "什么时候更新完啊？", 问题答案
    "keywords": "怎么，修改，密码", 问题关键词
    "sort": 1000, 排序号
    "start_time": 1627574400,
    "end_time": 1630339199,
    "helpful_count": 3,
    "unhelpful_count": 4,
    "remark": "备注？", 备注
    "status": 1, 状态：1：启用；0：禁用
    "valid_date_type": 2, 有效日期类型：1：永久；2：自定义
    "valid_date_start": "2021-07-30", 生效开始日期，当valid_date_type=2时有返回
    "valid_date_end": "2021-08-30", 生效结束日期，当valid_date_type=2时有返回
    "helpful_rate": "43%" 有助率
    }
    }
     */
    public function detail(Request $request)
    {
        $param = $request->only('id');
        //参数校验
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $request->id;

        $question = app('model_customer_service_question')
            ->select('id', 'name', 'answer', 'keywords', 'sort', 'start_time', 'end_time', 'helpful_count', 'unhelpful_count', 'remark', 'status')
            ->where('id', $id)->first();
        if (empty($question)) throw new BasicException(0, '参数错误，记录不存在');

        //生效时间
        if ($question->end_time == -1) {
            $question->valid_date_type = 1; //永久
        } else {
            $question->valid_date_type = 2; //自定义的其它生效时间
            $question->valid_date_start = date('Y-m-d', $question->start_time);
            $question->valid_date_end = date('Y-m-d', $question->end_time);
        }
        //计算有助率
        if ($question->helpful_count == 0) {
            $question->helpful_rate = '0%';
        } else {
            $question->helpful_rate = round($question->helpful_count / ($question->helpful_count + $question->unhelpful_count) * 100) . '%';
        }

        return Response::sendData($question);
    }

    /**
     * @api {put} /customer-service/question/status 编辑问题状态
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {int} id 问题id，必须
     *
     * @apiSuccessExample 成功响应
     * {
     * "code":200,
     * "data":1 修改后的状态：1：启用；0：禁用
     * }
     */
    public function editStatus(Request $request)
    {
        $param = $request->only('id');
        //参数校验
        $v = app('validator')->make($param,
            [
                'id' => 'required|integer|min:1',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $request->id;

        $question = app('model_customer_service_question')
            ->select('status')
            ->where('id', $id)
            ->first();
        if (empty($question)) throw new BasicException(0, '参数错误，记录不存在');

        $status = $question->status == 1 ? 0 : 1;

        $res = app('model_customer_service_question')->where('id', $id)->update(['status' => $status]);
        if ($res) {
            return Response::sendData($status);
        }
        throw new BasicException(0, '修改失败');
    }

    /**
     * @api {delete} /customer-service/question 删除问题
     *
     * @apiGroup 客服问题管理
     *
     * @apiParam {int} id 问题id，必须
     *
     * @apiSuccessExample 成功响应
     * {
     * "code":200,
     * "data":[]
     * }
     */
    public function del(Request $request)
    {
        $param = $request->only('id');
        //参数校验
        $v = app('validator')->make($param, [
            'id' => 'required|integer|min:1',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $request->id;

        $question = app('model_customer_service_question')
            ->select('status')
            ->where('id', $id)
            ->first();
        if (empty($question)) throw new BasicException(0, '参数错误，记录不存在');

        if ($question->status == 1) {
            throw new BasicException(0, '当前问题为启用状态，请先禁用再删除');
        }

        DB::beginTransaction();
        try {
            //删除问题
            app('model_customer_service_question')->where('id', $id)->delete();
            //删除问题关键词
            $questionKeywords = app('model_customer_service_question_keywords')
                ->select('id', 'question_ids')->where('question_ids', 'like', "%,$id,%")->get();
            foreach ($questionKeywords as $questionKeyword) {
                $newQuestionIds = str_replace(",$id", '', $questionKeyword->question_ids);
                if ($newQuestionIds == ',') {
                    app('model_customer_service_question_keywords')->where('id', $questionKeyword->id)->delete();
                } else {
                    app('model_customer_service_question_keywords')->where('id', $questionKeyword->id)
                        ->update(['question_ids' => $newQuestionIds]);
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            throw new BasicException(0, $e->getMessage());
        }
    }
}